package AtmSystem;

import java.util.*;
import java.io.*;

public class ClientDBIO {



    public ClientDB loadClientDB (String filename) throws IOException,
        FileNotFoundException {

        ClientDB myClientDB = new ClientDB();

        BufferedReader reader =
            new BufferedReader(new FileReader(filename));
        String line =  reader.readLine();

        while (line != null) {

            Client myClient = null;
            myClient = readClient(line);
            myClientDB.add(myClient);

            line =  reader.readLine();
        }

		reader.close();

        return myClientDB;
    }


    private Client readClient (String line) {

        StringTokenizer tokenizer = new StringTokenizer(line, " ");
		
		int userID = Integer.parseInt(tokenizer.nextToken());
		String username = tokenizer.nextToken();
		String password = tokenizer.nextToken();
		String email = tokenizer.nextToken();

        Client myClient =new Client ( userID, username,  password ,email);

        StringTokenizer bankToken = new StringTokenizer(tokenizer.nextToken(),"+");

		while( bankToken.hasMoreTokens() )
		{
		StringTokenizer bankInfoToken =new StringTokenizer (bankToken.nextToken(),",");

		int cardNumber =Integer.parseInt( bankInfoToken.nextToken() );
		double balance = Double.parseDouble(bankInfoToken.nextToken());

	    myClient.addBankAccount(cardNumber, balance);
		}

      return myClient;
      }

	  public boolean writerClientDB (String filename ,ClientDB newClientDB) throws IOException,
        FileNotFoundException {
	 try
     {
		PrintWriter writer=
            new PrintWriter (new FileWriter(filename,false));

        for (int index = 0; index <newClientDB.getNumbers();index++ )
			{
			Client myClient= newClientDB.get(index);
			writer.println(writeClient(myClient));
			}

			writer.close();
        return true;
		}
     catch (FileNotFoundException e)
		{
		 return false;
		}   
	}


   private String writeClient(Client newClient) {

		String clientInfo="";
		clientInfo+= newClient.getUserID();
		clientInfo+= " ";
		clientInfo+= newClient.getUsername();
		clientInfo+= " ";
		clientInfo+= newClient.getPassword();
		clientInfo+= " ";
		clientInfo+= newClient.getEmail();
		clientInfo+= " ";
		
		BankAccountDB myBankAccountDB = newClient.getBankAccountDB();

		 for (int index = 0; index <myBankAccountDB.getNumbers();index++ )
        {
			BankAccount myBankAccount=myBankAccountDB.get(index);
			clientInfo+= myBankAccount.getCardNumber();
			clientInfo+= ",";
			clientInfo+= myBankAccount.getBalance();
			clientInfo+= "+";
        } 
		
      return clientInfo;      
	}
}
